"""
注册表管理类 - 使用当前用户权限
"""
import winreg
import os
from tkinter import messagebox

class RegistryManager:
    """注册表管理器"""

    def __init__(self):
        self.base_key = winreg.HKEY_CLASSES_ROOT
        self.menu_base_path = 'Directory\\Background\\shell'

    def add_menu(self, menu_name, command_path, icon_path=None):
        """
        添加右键菜单

        Args:
            menu_name: 菜单显示名称
            command_path: 可执行文件路径
            icon_path: 图标路径（可选）

        Returns:
            bool: 操作是否成功
        """
        try:
            # 验证输入
            if not menu_name or not command_path:
                messagebox.showwarning("警告", "菜单名称和命令路径不能为空")
                return False

            # 检查文件是否存在
            if not os.path.exists(command_path):
                messagebox.showerror("错误", f"文件不存在: {command_path}")
                return False

            # 检查菜单是否已存在
            if self._menu_exists(menu_name):
                if not messagebox.askyesno("提示", f"菜单 '{menu_name}' 已存在，是否覆盖？"):
                    return False

            # 创建菜单
            success = self._create_menu(menu_name, command_path, icon_path)

            if success:
                # messagebox.showinfo("成功", "右键菜单添加成功！")
                return True
            else:
                return False

        except Exception as e:
            messagebox.showerror("错误", f"添加失败: {str(e)}")
            return False

    def delete_menu(self, menu_name):
        """
        删除右键菜单

        Args:
            menu_name: 菜单名称

        Returns:
            bool: 操作是否成功
        """
        try:
            if not self._menu_exists(menu_name):
                messagebox.showwarning("警告", f"菜单 '{menu_name}' 不存在")
                return False

            # 删除菜单
            menu_key_path = f'{self.menu_base_path}\\{menu_name}'
            command_key_path = f'{menu_key_path}\\command'

            try:
                # 先删除command子键
                winreg.DeleteKey(self.base_key, command_key_path)
            except FileNotFoundError:
                pass  # 子键可能不存在

            try:
                # 再删除主键
                winreg.DeleteKey(self.base_key, menu_key_path)
            except FileNotFoundError:
                pass  # 主键可能不存在

            return True

        except Exception as e:
            messagebox.showerror("错误", f"删除失败: {str(e)}")
            return False

    def _menu_exists(self, menu_name):
        """检查菜单是否存在"""
        menu_key_path = f'{self.menu_base_path}\\{menu_name}'
        try:
            with winreg.OpenKey(self.base_key, menu_key_path):
                return True
        except (FileNotFoundError, OSError):
            return False

    def _create_menu(self, menu_name, command_path, icon_path=None):
        """创建菜单注册表项"""
        try:
            menu_key_path = f'{self.menu_base_path}\\{menu_name}'
            command_key_path = f'{menu_key_path}\\command'

            # 修复路径斜杠问题 - 关键修复
            # 将路径中的正斜杠转换为反斜杠，并确保正确引用
            normalized_command_path = command_path.replace('/', '\\')
            normalized_icon_path = icon_path.replace('/', '\\') if icon_path else None

            # 格式化命令路径
            if ' ' in normalized_command_path:
                # 如果路径中有空格，用双引号包围
                full_command = f'"{normalized_command_path}" "%V"'
            else:
                full_command = f'{normalized_command_path} "%V"'

            print(f"创建菜单: {menu_name}")
            print(f"原始命令路径: {command_path}")
            print(f"标准化命令路径: {normalized_command_path}")
            print(f"完整命令: {full_command}")

            # 创建主菜单项
            with winreg.CreateKey(self.base_key, menu_key_path) as key:
                winreg.SetValue(key, '', winreg.REG_SZ, menu_name)

                # 添加图标（如果提供）
                if normalized_icon_path and os.path.exists(normalized_icon_path):
                    winreg.SetValueEx(key, "Icon", 0, winreg.REG_SZ, normalized_icon_path)
                    print(f"图标路径: {normalized_icon_path}")
                elif normalized_icon_path:
                    print(f"警告: 图标文件不存在: {normalized_icon_path}")
                else:
                    # 如果没有提供图标路径，使用可执行文件自身作为图标
                    winreg.SetValueEx(key, "Icon", 0, winreg.REG_SZ, normalized_command_path)
                    print(f"使用程序自身作为图标: {normalized_command_path}")

            # 创建命令子项
            with winreg.CreateKey(self.base_key, command_key_path) as command_key:
                winreg.SetValue(command_key, '', winreg.REG_SZ, full_command)

            return True

        except Exception as e:
            print(f"创建注册表项时出错: {str(e)}")
            raise

    def list_menus(self):
        """列出所有已注册的菜单（用于调试）"""
        try:
            base_key_path = self.menu_base_path
            menus = []

            with winreg.OpenKey(self.base_key, base_key_path) as key:
                i = 0
                while True:
                    try:
                        menu_name = winreg.EnumKey(key, i)
                        menus.append(menu_name)
                        i += 1
                    except WindowsError:
                        break

            return menus
        except FileNotFoundError:
            return []